package com.sws.orderMS.command.impl;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.sws.orderMS.OrderMSDao;
import com.sws.orderMS.command.UserCommand;
import com.sws.orderMS.pojo.Client;
import com.sws.orderMS.pojo.User;
import com.sws.orderMS.tool.Tool;

public class RechargeCommand extends UserCommand {

	public RechargeCommand(User userProfile) {
		super(userProfile);
	}

	@Override
	public void execute() {
		OrderMSDao dao = new OrderMSDao();
		Client client = (Client)userProfile;
		double myBalance = dao.getUserBalance(client);
		Tool.printMsg(client.getName() + "的个人账户余额: " + myBalance);
		String amount = Tool.askUserInputNotNull("请输入充值金额: ");
		if (!isValidInput(amount)) {
			Tool.printMsg("Invalid input");
			return;
		}
		double balance = myBalance + Double.parseDouble(amount);
		int affectRows = dao.updateUserBalance(balance, client.getId());
		if (affectRows > 0) {
			client.getWallet().setBalance(balance);
			Tool.printMsg("充值成功!");
			Tool.printMsg(client.getName() + "的个人账户余额: " + client.getWallet().getBalance());
		} else {
			Tool.printMsg("充值失败!");
		}
	}
	
	public boolean isValidInput(String input) {
		Pattern pattern = Pattern.compile("[A-Za-z]");
		Matcher matcher = pattern.matcher(input.trim());
		if (matcher.find()) {
			return false;
		}
		return true;
	}

}
